package com.bradz.mytv;

import java.util.ArrayList;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

//Adds the valid urls to the database for commercials later on
public class classFetchInternet extends AsyncTask<Object, Void, Void> {
	
    classCommercialParser cParse;
    private classChannelDatabase channel_database;
    private ArrayList <classUrlListAttributes> Url_List;
    private String holder = "";

    @Override
    protected Void doInBackground(Object... params) {
    	String urls = (String) params[0];
    	Context context = (Context) params[1];
    	channel_database = new classChannelDatabase(context);
    	Url_List = new ArrayList <classUrlListAttributes>();
        try {
        	cParse = new classCommercialParser(urls);
        	for(int i = 0; i < cParse.get_list().size();i++){
        		int vid_index = cParse.get_list().get(i).indexOf("?v=");
        		int vid_end = cParse.get_list().get(i).indexOf("&");
        		classXMLParser x_parser = new classXMLParser();
        		if(vid_index != -1){
    	    		String video_reference = cParse.get_list().get(i).substring(vid_index+3, vid_end == -1?cParse.get_list().get(i).length():vid_end);
    	    		x_parser.set_url("http://gdata.youtube.com/feeds/api/videos/" + video_reference);
    	    		holder = x_parser.parse_for_youtube();
    	    		if (!holder.isEmpty()){
    	    			Url_List.add(new classUrlListAttributes(cParse.get_list().get(i),holder));
    	    		}
        		}
        	}
            return null;
        } catch (Exception e) {
        	Log.i("myTV - fetchInternet", "Error: " + e);
            return null;
        }
    }

    @Override
    protected void onPostExecute(Void result) {
    	Log.i("myTV - fetchInternet", "Post Execute");
    	for(int i = 0; i < Url_List.size();i++){
	    	channel_database.add_commercial(Url_List.get(i).get_parsed(), Url_List.get(i).get_youtube(), 60);
    	}
    	Log.i("myTV - networkHolder", "Data received");
		return;
    }
 }